package com.yejiali.backend.util;

import com.yejiali.backend.entity.vo.TokenInfo;
import com.yejiali.backend.entity.vo.WeChatUser;

import javax.swing.plaf.nimbus.State;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

/**
 * @Author:yejiali
 * @Date:2025/7/15-07-15-14:36
 * @Decsription:com.yejiali.backend.util
 * @Version:1.0
 */
public class WeChatUtil {
    private static final String appId = "wx5036e8cb2f8f56b5";
    private static final String secret = "03dd3469611f3889838c8f33c3eb868a";

    /**
     * 获取用户个人信息
     *
     * @param code 授权码
     * @return user 用户消息封装对象
     */
    public static WeChatUser getUserInfo(String code) throws IOException, InterruptedException {
        //获取token信息
        //HTTP客户端API
        HttpClient httpClient = HttpClient.newHttpClient();
        //请求url
        //String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String tokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, secret, code);
        //发起请求返回TokenInfo对象
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(tokenUrl))
                .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        String responseResult = "";
        //响应成功
        if (response.statusCode() == 200) {
            responseResult = response.body();
        } else {
            //响应失败
            throw new RuntimeException("获取token信息失败");
        }
        System.out.println("获取access_token信息" + responseResult);
        //解析TokenInfo对象
        TokenInfo tokenInfo = JsonUtil.parse(responseResult, TokenInfo.class);
        //获取access_token
        String accessToken = tokenInfo.getAccessToken();
        //拿token去获取用户信息
        //请求url
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + tokenInfo.getOpenId() + "&lang=zh_CN";
        HttpRequest smsRequest = HttpRequest.newBuilder()
                .uri(URI.create(userInfoUrl))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(smsRequest, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (httpResponse.statusCode() == 200) {
            responseResult = httpResponse.body();
        }else{
            throw new RuntimeException("获取用户信息失败");
        }
        System.out.println("获取用户信息" + httpResponse.body());
        //解析用户信息
        WeChatUser weChatUser = JsonUtil.parse(responseResult, WeChatUser.class);
        return weChatUser;
    }

}
